package lunchy.data.classes;

import java.util.ArrayList;
import java.util.List;

import lunchy.data.interfaces.ILunchyMenu;
import lunchy.data.interfaces.ILunchyMenuDAO;
import lunchy.data.interfaces.ILunchyMenuGroup;
import lunchy.data.interfaces.ILunchyMenuItem;
import lunchy.main.CLunchyApplication;
import lunchy.util.*;
import org.hibernate.Session;
import org.hibernate.Query;

public class CLunchyDBMenuDAO implements ILunchyMenuDAO
{
	private Session session = null;
	
	public CLunchyDBMenuDAO()
	{
		session = CLunchyHibernateUtil.getSessionFactory().openSession();
	}
	
	public boolean saveMenu(ILunchyMenu menu)
	{
		try
		{
			session.beginTransaction();
			
			for (ILunchyMenuGroup iLunchyMenuGroup : menu.getMenuGroups())
				session.saveOrUpdate(iLunchyMenuGroup);
			
			session.getTransaction().commit();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		return true;
	}

	public ILunchyMenu getActiveMenuItems()
	{
		ILunchyMenu menu = new CLunchyMenu();
		List<ILunchyMenuGroup> groups = new ArrayList<ILunchyMenuGroup>();
		
		try
		{	
			Query query = session.createQuery("from CLunchyMenuGroup");
			//Query query = session.createQuery("from CLunchyMenuGroup where CLunchyMenuGroup.items[0].active = :active").setBoolean("active", true);	
			groups = (List<ILunchyMenuGroup>) query.list();
			
			for (ILunchyMenuGroup iLunchyMenuGroup : groups)
			{
				ILunchyMenuGroup tempGroup = new CLunchyMenuGroup();
				tempGroup.setId(iLunchyMenuGroup.getId());
				tempGroup.setName(iLunchyMenuGroup.getName());
				menu.setMaxGroupId(iLunchyMenuGroup.getId());
				
				for (ILunchyMenuItem item : iLunchyMenuGroup.getItems())
				{
					if(item.isActive())
						tempGroup.addMenuGroupItem(item);
					
					menu.setMaxItemId(item.getId());
				}

				menu.addMenuGroup(tempGroup);
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

	    return menu;
	}

	public ILunchyMenu getAllMenuItems()
	{
		ILunchyMenu menu = new CLunchyMenu();
		List<ILunchyMenuGroup> groups = new ArrayList<ILunchyMenuGroup>();
		
		try
		{
			Query query = session.createQuery("from CLunchyMenuGroup");	
			groups = (List<ILunchyMenuGroup>) query.list();
			
			for (ILunchyMenuGroup iLunchyMenuGroup : groups)
			{
				menu.setMaxGroupId(iLunchyMenuGroup.getId());
				
				for (ILunchyMenuItem item : iLunchyMenuGroup.getItems())
				{	
					menu.setMaxItemId(item.getId());
				}
				
				menu.addMenuGroup(iLunchyMenuGroup);
			}
		}
		catch (Exception e)
		{
			
		}

	    return menu;
	}

}
